
package com.tools.cleanmaster.ui.activity;

import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.CleanConstant;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.candysaver.CandySaverNotification;
import com.tools.cleanmaster.ui.base.SingleActivity;
import com.tools.cleanmaster.ui.view.header.HeadHelper;

public class ChargingSettingActivity extends SingleActivity {

    private ImageView mSwitch;
    private boolean mFromStatusBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.charge_setting_view);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.common_background_blue), 0);

        HeadHelper.setupMainHeader(this, R.id.titlebar, R.string.charge_status_title, this).hideSettingButton().setBackgroundColor();

        // 如果从通知栏进入页面，将开关打开
        int extraFrom = getIntent().getIntExtra(CleanConstant.EXTRA_FROM_KEY, -1);
        mFromStatusBar = extraFrom == CleanConstant.EXTRA_FROM_VALUE_STATUSBAR;

        mSwitch = findViewById(R.id.setting_switch);
        mSwitch.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean chargingEnable = imContext.getCleanSharedPrefManager().getChargingEnable();
                imContext.getCleanSharedPrefManager().setChargingEnable(!chargingEnable);
                refresh();

                if(chargingEnable){
                    GARecordUtils.report(imContext, CleanGAConstant.C_FUNC, CleanGAConstant.A_SWITCH, CleanGAConstant.L_SMART_CHARGE);
                }
            }
        });

        clearScreenSaverNotification();
    }

    @Override
    protected void doOnResume() {
        refresh();
    }

    private void refresh() {
        boolean isScreenSaverOpen = imContext.getCleanSharedPrefManager().getChargingEnable();
        mSwitch.setImageDrawable(isScreenSaverOpen ? getResources().getDrawable(R.drawable.item_switch_on) : getResources().getDrawable(R.drawable.item_switch_off));
    }

    private void clearScreenSaverNotification() {
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.cancel(CandySaverNotification.NOTIFICATION_NAME, CandySaverNotification.NOTIFICATION_ID);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        if (mFromStatusBar) {
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);
        }
    }
}
